
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;



public class OwnerLogin extends JScrollPane{
	private JPasswordField jpwfOwnerPass = new JPasswordField(15);
	private  JTextField jtfOwnerName = new JTextField(15);
	private JTextArea jtaInfo = new JTextArea(25,15);
	public static JButton jbtLogin = new JButton("Log-In");
	
	// Connection
	private Connection connection;
	
	// Save userName and password
	protected static String password;
	protected static String userName;
	
	public OwnerLogin(){
		//Edit display panel information
		jtaInfo.setEditable(false);
		//jtaInfo.setBackground(new Color(233,236,238));
		
		
		// Create a panel to group the password-field and the user-id text-field
		JPanel userIdPassPanel = new JPanel(new FlowLayout());
		userIdPassPanel.add(new JLabel("User ID "));
		userIdPassPanel.add(jtfOwnerName);
		userIdPassPanel.add(new JLabel("Password: "));
		userIdPassPanel.add(jpwfOwnerPass);
		userIdPassPanel.add(jbtLogin);
		
		
		JPanel main = new JPanel(new BorderLayout());
		main.add(userIdPassPanel, BorderLayout.CENTER);
		//main.add(jbtLogin, BorderLayout.EAST);
		main.add(jtaInfo, BorderLayout.SOUTH);
		
		
		// Add an action listener to the JButton jbtLogin
		jbtLogin.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				validateOwner();
			}
		});
		
		
		this.setViewportView(main);
	}
	
	
	
	private void validateOwner(){
		// Load Drive and connect to the database
		try{
			// Load the driver
			Class.forName("com.mysql.jdbc.Driver");
			//System.out.println("Driver loaded");
			
			// Connect to the database
			connection = DriverManager.getConnection("jdbc:mysql://db.student.chalmers.se:3306/spilkov", "spilkov","pfG87H26");
			//System.out.println("Database connected");
			
			// Compare entered value for user name and password with the database
			PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM restaurant WHERE restaurant.owner_username = ? AND restaurant.ownerPassword = ?");
			 userName = jtfOwnerName.getText();
			 password = String.valueOf((jpwfOwnerPass.getPassword()));
			
			
			preparedStatement.setString(1,userName );
			preparedStatement.setString(2, password);
			
			ResultSet resultSet = preparedStatement.executeQuery();
			
			if(userName.equals("")){
				jtaInfo.setText("User name or password field empty");
			}
			
			else if(resultSet.next() && !userName.equals("") ){
				jtaInfo.setText("Congratulation you connected to your account successfully");
				MainFrame.restaurantCardLayout.show(MainFrame.restaurantContainer, "ownerChoice");
			}else if(!userName.equals("")){
				jtaInfo.setText("Invalid User id or password");
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
	}


}
